package ticket;

public class Ticket extends Thread {
    private TicketPool ticket_pool;
    private int ticket_require;
    private int tickets = 0;

    /*
    构造函数，两个参数，tpl代表目标票池，treq代表需要抢的票数
    */
    public Ticket(TicketPool tpl, int treq) {
        ticket_pool = tpl;
        ticket_require = treq;
    }

    /*
    抢票过程：查询目标漂池剩余的票数
        如果剩余票数大于等于需要的票数，则在目标漂池中抢走需要的票数
        如果剩余票数小于需要的票数，则在目标漂池中抢走剩余票数
    */
    public void run() {
        synchronized (ticket_pool) {
            if (tickets < ticket_require) {
                int rest = ticket_pool.getRest();
                if (rest >= ticket_require) {
                    ticket_pool.reduceRest(ticket_require);
                    tickets += ticket_require;
                }
                else {
                    ticket_pool.reduceRest(rest);
                    tickets += rest;
                }
            }
        }
    }

    /*
    查询抢票结果：返回抢到的票的数量
    */
    public int getObtained() {
        return tickets;
    }
}
